package com.yangyang.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageInfo;
import com.yangyang.entity.Order;
import com.yangyang.entity.QueryVo;
import com.yangyang.entity.User;
import com.yangyang.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class OrderController {

    @Autowired
    OrderService service;

    @RequestMapping("tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("login")
    public String login(HttpServletRequest request, User user){
        user = service.getUser(user);
        if (user != null){
            request.getSession().setAttribute("user",user);
            return "index";
        }
        return "";
    }

    @RequestMapping("list")
    public String list(HttpServletRequest request, QueryVo vo,
                       @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize){
        PageInfo<Order> pg = service.list(vo,pageNum,pageSize);
        double sum = 0;
        SimpleDateFormat sdf = new SimpleDateFormat();
        String date = sdf.format(new Date());
        date = date.substring(3,5);
        System.out.println("系统日期:"+date);
        List<Order> list = service.getlist();
        for (Order order : list) {
            String s = sdf.format(order.getOrderDate());
            //获取订单的月份
            s = s.substring(3,5);
            System.out.println("订单日期:"+s);
            if (s.equals(date)){
                sum += order.getOrderMoney();
            }

        }

        System.out.println("累计金额"+sum);
        request.setAttribute("sum",sum);
        request.setAttribute("pg",pg);
        request.setAttribute("vo",vo);
        return "list";
    }

    @RequestMapping("toadd")
    public String toadd(HttpServletRequest request){
        Snowflake snowflake = IdUtil.createSnowflake(31, 31);
        long l = snowflake.nextId();
        request.setAttribute("l",l);
        return "add";
    }

    @RequestMapping("add")
    public String add(Order order){
        int i = service.add(order);
        return "redirect:list";
    }
}
